package com.atguigu.gulimall.order.web;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.order.domain.vo.OrderConfirmVO;
import com.atguigu.gulimall.order.domain.vo.SubmitOrderRespVO;
import com.atguigu.gulimall.order.domain.vo.SubmitOrderVO;
import com.atguigu.gulimall.order.service.OrderService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lhj
 * @Date 2024/5/1 16:37
 */
@Slf4j
@Controller
public class OrderTradeController {
    
    @Autowired
    OrderService orderService;

    /**
     * 订单确认页数据
     * @param model
     * @return
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) {
        try {
            //获取订单确认页数据
            OrderConfirmVO orderConfirmVO = orderService.toTrade();
            model.addAttribute("orderConfirmData", orderConfirmVO);
            return "confirm";
        } catch (Exception e) {
            log.info("OrderTradeController.toTrade get order confirm page data exception", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("code", BizCodeEnum.GET_ORDER_CONFIRM_PAGE_DATA_ERROR.getCode());
            errorMap.put("msg", BizCodeEnum.GET_ORDER_CONFIRM_PAGE_DATA_ERROR.getMsg());
            model.addAttribute("errors", errorMap);
            return "redirect://cart.gulimall.com/cart.html";
        }
    }

    /**
     * 提交订单
     * @param submitOrderVO
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(SubmitOrderVO submitOrderVO, Model model, RedirectAttributes redirectAttributes) {
        SubmitOrderRespVO submitOrderRespVO = orderService.submitOrder(submitOrderVO);
        if (submitOrderRespVO.getCode() == 0) {
            model.addAttribute("submitOrderResp", submitOrderRespVO);
            return "pay";
        }
        String errorMsg = submitOrderRespVO.getMsg();
        redirectAttributes.addFlashAttribute("errorMsg", errorMsg);
        return "redirect://cart.gulimall.com/confirm.html";
    }
    
}
